<template>
  <div class="app-container">
    <!--  搜索框  -->
    <search-form :data="searchFormObj.searchData" :field-list="searchFormObj.fieldList"
      :listTypeInfo="searchFormObj.listTypeInfo" @handleSearch="handleQuery" @handleReset="handleReset" />
    <!--  按钮  -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:role:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:role:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:role:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:role:export']">
          导出
        </el-button>
      </el-col>
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>
    <!--  表格 -->
    <hk-table :loading="loading" :tableData="roleList" :showIndex="true" :tableColumns="tableLabel" :operate="true" :table-height="80"
      :selection="true" :total="total" :queryParams="queryParams" @handleSelectionChange="handleSelectionChange"
      @changePage="pageChangePage" :commonFixed="false" :selectFn="selectable">
      <template #status="scope">
        <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
          @change="handleStatusChange(scope.row)" :disabled="scope.row.roleType == 1"></el-switch>
      </template>

      <template #operate="scope">
        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
          v-hasPermi="['system:role:edit']">{{ scope.row.roleType == 1 ? '详情' : '修改'}}
        </el-button>
        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
          v-hasPermi="['system:role:remove']" v-if="scope.row.roleType != 1">删除
        </el-button>
        <!-- <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
          v-hasPermi="['system:role:edit']">
          <span class="el-dropdown-link">
            <i class="el-icon-d-arrow-right el-icon&#45;&#45;right"></i>更多
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check" v-hasPermi="['system:role:edit']">
              数据权限
            </el-dropdown-item>
            <el-dropdown-item command="handleAuthUser" icon="el-icon-user" v-hasPermi="['system:role:edit']">分配用户
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
      </template>
    </hk-table>

    <!-- 添加或修改角色配置对话框 -->
    <add-dialog ref="addDialogRef" :title="title" @submitForm="submitForm" :statusDict="statusDict"/>
  </div>
</template>

<script>
import { listRole, delRole, changeRoleStatus } from '@/api/system/role'
import searchForm from '@/components/HKSearchform/index.vue'
import addDialog from './form'
import datas from './data/datas'
import HkTable from '@/components/HKTable/index.vue'

export default {
  name: 'Role',
  components: { searchForm, addDialog, HkTable },
  dicts: ['role_status'],
  data() {
    return {
      ...datas,
      //   搜索框数据
      searchFormObj: {
        fieldList: [{
          label: '角色名称',
          type: 'input',
          field: 'name'
        },
        {
          label: '权限字符',
          type: 'input',
          field: 'code'
        },
       /*  {
          label: '状态',
          type: 'select',
          field: 'status',
          list: 'statusList',
          clearable: true
        } */
      ],
        searchData: {},
        btnHidden: true,
        listTypeInfo: {
          statusList: []
        },
        //  是否有额外的参数
        isNeedResetExtraParam: false
      },
      statusDict: []
    }
  },
  created() {
    this.queryParams.current=1;
    this.queryParams.size=10
    this.getList()
  },
  methods: {
    onDictReady(dict) {
      this.searchFormObj.listTypeInfo.statusList = dict.type.role_status
      this.statusDict = dict.type.role_status
    },
    /** 查询角色列表 */
    getList() {
      listRole(Object.assign({}, this.queryParams, this.searchForm)).then(res => {
        this.roleList = res.list
        this.total = res.total
      })
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status == 0 ? '启用' : '停用'
      this.$modal.confirm('确认要' + text + '[' + row.name + ']角色吗？').then(function () {
        return changeRoleStatus(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
        this.getList()
      }).catch(function () {
        row.status = row.status == 0 ? 1 : 0
      })
    },
    pageChangePage(data) {
      this.queryParams = data
      this.getList();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
    },

    /** 搜索按钮操作 */
    handleQuery(data) {
      this.searchForm = data
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset(data) {
      this.searchForm = data
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    selectable(row) {
      return row.roleType != 1
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleDataScope':
          this.handleDataScope(row)
          break
        case 'handleAuthUser':
          this.handleAuthUser(row)
          break
        default:
          break
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.addDialogRef.show("")
      this.title = '添加角色'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.addDialogRef.show(row.id)
      this.title = row.type==1?'角色详情':'修改角色'
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== '2') {
        // this.$refs.deptRef.setCheckedKeys([])
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      const roleDeptTreeselect = this.getRoleDeptTreeselect(row.id)
      getRole(row.id).then(response => {
        this.$refs.deptRef.openDataScope = true
        this.$nextTick(() => {
          roleDeptTreeselect.then(res => {
            this.form = {
              id: response.id,
              code: response.code,
              name: response.name,
              dataScope: response.dataScope.toString(),
              deptIds: res.checkedKeys
            }
          })
        })
        this.title = '分配数据权限'
      })
    },
    /** 分配用户操作 */
    handleAuthUser: function (row) {
      const roleId = row.id
      this.$router.push('/system/role-auth/user/' + roleId)
    },
    /** 提交按钮 */
    submitForm: function (value) {
      if (value) {
        this.getList()
      }
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.id != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys()
        dataScope(this.form).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.openDataScope = false
          this.getList()
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids
      this.$modal.confirm('确定要删除该项角色数据？').then(function () {
        return delRole(roleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(window.baseUrl+'/system/role/export', {
        ...this.queryParams
      }, `角色信息表_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table{
  margin-top:0px !important;
}
.targetTable{
  flex:1;
}
.app-container{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>